package com.youdianstar.app.ui

import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.youdianstar.app.common.MAX_COUNT_ORDER
import com.youdianstar.app.common.MIN_COUNT_LIMIT

import com.youdianstar.app.support.ApiRepository
import com.youdianstar.app.common.base.BaseViewModel
import com.youdianstar.app.entity.OrderInfo
import com.youdianstar.app.entity.NewOrderInfo
import com.youdianstar.app.entity.OrderDetailInfo
import com.youdianstar.app.common.event.NetEventLiveData
import com.youdianstar.app.common.event.NetStateLiveData

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch


/**
 * File: OrderViewModel
 * Author: 82149 Create: 2021/11/11 16:41
 * Changes (from 2021/11/11)
 * --------------------------------------------------
 * description: 订单相关
 * ---------------------------------------------------
 *
 */
class OrderViewModel (private val repo: ApiRepository) : BaseViewModel(){
    val listEventLiveData = NetEventLiveData()
    /**
     * 请求订单列表数据
     */
    fun getOrderListData(): Flow<PagingData<Any>> =
        repo.getOrderListData(listEventLiveData).cachedIn(viewModelScope)

    /**
     * 新订单列表数据
     */
    val newOrderListLiveData = NetStateLiveData<List<Any>>()

    /**
     * 获取新订单列表数据
     */
    fun getNewOrderList() {
        viewModelScope.launch(Dispatchers.IO) {
            repo.getNewOrderList(newOrderListLiveData)
        }
    }


    /*订单详情数据*/
    val orderDetailsFiled = androidx.databinding.ObservableField<OrderInfo>()
    
    /*订单详情原始数据（新接口格式）- 临时保存，供详情页直接使用 */
    var currentOrderDetailInfo: OrderDetailInfo? = null

    val detailNetLiveData = NetStateLiveData<OrderInfo>()

    /**
     * 获取订单详情数据
     *
     * @param orderNo 订单号
     */
    fun getOrderDetail(orderNo: String){
//        showLoading()
        viewModelScope.launch (Dispatchers.IO){
            repo.getOrderDetails(orderNo, detailNetLiveData) { detailInfo ->
                // 保存原始OrderDetailInfo数据，供详情页直接使用
                currentOrderDetailInfo = detailInfo
            }
        }
    }


    private var requestJob : Job? = null
    private var detailNo:String? = null
    /**
     * 使用Flow 轮询订单详情: 5秒一次
     * @param orderNo 订单号
     */
    fun countDetailRequest(orderNo: String){
        detailNo = orderNo
        requestJob?.cancel()
        requestJob = flow {
            for (i in 0..MAX_COUNT_ORDER){
                emit(i)
                delay(5000)
            }
        }.flowOn(Dispatchers.Default)
            .onCompletion {
                //Job cancel 会走这里
            }
            .onEach {
                //requestCountEvent.value = it
                getOrderDetail(orderNo)
            }
            .flowOn(Dispatchers.Main)
            .launchIn(viewModelScope)
    }

    fun cancelDetailCount(){
        requestJob?.cancel()
    }
}